﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Collections.Specialized;
using System.Threading.Tasks;
using System.Threading;
using CrawlerCore;
using WCrawlerLib;
using System.Configuration;
using System.Reflection;

namespace WCrawler.Controls
{
    public partial class ucForum : System.Web.UI.UserControl
    {
        /// <summary>
        /// Biến dùng cho thể hiện số thứ tự của một forum
        /// </summary>
        private int _index = 0;

        /// <summary>
        /// http://aspdotnetcodebook.blogspot.com/2009/11/event-bubbling-in-aspnet.html
        /// </summary>
        public int SelectedValue
        {
            get
            {
                return (int)this.gridViewForums.SelectedDataKey["ForumId"];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //gridViewForums.SelectRow(0);
                //Set connectstring for dll library
                WCrawlerLib.AppSettings.my_mpconfigConnectionString = ConfigurationManager.ConnectionStrings["my_mpconfigConnectionString"].ToString();

                gridViewForums.PageSize = 10;
                LocationDropDownList.Items.Insert(0, new ListItem());
                LocationDropDownList.DataBind();
                ForumTypeDropDownList.Items.Insert(0, new ListItem());
                ForumTypeDropDownList.DataBind();
                ContentTypeDropDownList.Items.Insert(0, new ListItem());
                ContentTypeDropDownList.DataBind();
                LanguageDropDownList.Items.Insert(0, new ListItem());
                LanguageDropDownList.DataBind();
                GroupDropDownList.Items.Insert(0, new ListItem());
                GroupDropDownList.DataBind();
                
                StatusCodeDropDownList.Items.Insert(0, new ListItem());
                StatusCodeDropDownList.DataBind();

                dropDownListViewContent.SelectedIndex = 0;
                dropDownListViewContent_SelectedIndexChanged(null, null);

                LoginStatusDropDownList.Items.Insert(0, new ListItem());
            }
            //else
            //{
            //    int count = 0;
            //    if (Session["Count"] != null)
            //    {
            //        count = (int)Session["Count"] + 1;
            //    }
            //    Session["Count"] = count;
                    
            //}
        }

        #region EventHandler user control

        public event EventHandler BubbleIndexChanged;
        protected void gridViewForums_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (BubbleIndexChanged != null)
                BubbleIndexChanged(sender, e);
        }

        #endregion

        protected void gridViewForums_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
                _index = gridViewForums.PageSize * gridViewForums.PageIndex + 1;
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //if (e.Row.FindControl("hyperLinkUrl") != null)
                //{
                //    HyperLink hyperLinkUrl = (HyperLink)e.Row.FindControl("hyperLinkUrl");
                //    Label defaultUrl = (Label)e.Row.FindControl("lblDefaultUrl");
                //    hyperLinkUrl.NavigateUrl = hyperLinkUrl.Text + "/" + defaultUrl.Text;
                //}

                //Create order numbers
                ((Label)e.Row.FindControl("lblNum")).Text = (_index++).ToString();
                if (e.Row.FindControl("imgFlag") != null)
                {
                    System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgFlag");
                    if (img.ImageUrl == "")
                        img.Visible = false;
                }
            }
        }

        protected void dropDownListViewContent_SelectedIndexChanged(object sender, EventArgs e)
        {
            string pattern = "";
            //set all columns to visible = false;
            foreach (DataControlField col in gridViewForums.Columns)
                col.Visible = false;

            if (dropDownListViewContent.SelectedIndex == 0)         //1. View Forum Content
                pattern = "Select|#|Url|Type|Content|Language|Location|AlexaRank|Group|Account|Notes|IsAllowSearch|IsApproved";
            else if (dropDownListViewContent.SelectedIndex == 1)    //2. View Login Account
                pattern = "Select|#|Url|Type|Content|Location|AlexaRank|Account|UserId|LoginDate|LoginStatus";
            else if (dropDownListViewContent.SelectedIndex == 2)    //3. View Settings
                pattern = "Select|#|Url|Type|Content|Location|AlexaRank|DefaultUrl|IsIcons|IsTags|IsReCaptcha|IsHideTag|IsPrefix|IsHostContraint";
            else if (dropDownListViewContent.SelectedIndex == 3)    //3. View Messages
                pattern = "Select|#|Url|Type|Content|Location|AlexaRank|StatusCode|ErrorReport|Notes";
            foreach (DataControlField col in gridViewForums.Columns)
                if (pattern.Contains(col.HeaderText))
                    col.Visible = true;
            
        }

        public IQueryable<Forum> SearchQuery()
        {
            Forum obj = new Forum();
            var forumsQuery = obj.GetAll().ContainsUrl(txtSearchUrl.Text)
                                          .WhereLocation(LocationDropDownList.SelectedValue)
                                          .WhereForumType(ForumTypeDropDownList.SelectedValue)
                                          .WhereContentType(ContentTypeDropDownList.SelectedValue)
                                          .WhereLanguage(LanguageDropDownList.SelectedValue)
                                          .WhereGroup(GroupDropDownList.SelectedValue)
                                          .IsLoginStatus(LoginStatusDropDownList.SelectedValue)
                                          .WhereStatusCode(StatusCodeDropDownList.SelectedValue)
                                          .IsTags(chkUseTag.Checked)
                                          .IsIcons(chkUseIcons.Checked)
                                          .IsReCaptcha(chkUseReCaptcha.Checked)
                                          .IsHideTag(chkUseHideTag.Checked)
                                          .IsPrefix(chkUsePrefix.Checked)
                                          .IsHostConstraint(chkIsHostContraint.Checked);

            return forumsQuery;
        }

        protected void ForumLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            e.Result = SearchQuery();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            gridViewForums.DataBind();
        }

        protected void dropDownListNumberOfRows_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListNumberOfRows.SelectedIndex != (dropDownListNumberOfRows.Items.Count - 1))
            {
                gridViewForums.AllowPaging = true;
                gridViewForums.PageSize = int.Parse(dropDownListNumberOfRows.SelectedItem.Value);
            }
            else
            {
                gridViewForums.AllowPaging = false;
            }
        }

        protected void btnAddNewForum_Click(object sender, EventArgs e)
        {
            mdlPopup.Show();
            //if (!string.IsNullOrEmpty(txtNewForumUrl.Text))
            //{
            //    Forum obj = new Forum();
            //    if (obj.AddForum(txtNewForumUrl.Text))
            //        lblMessage.Text = "Add complete!";
            //    else
            //        lblMessage.Text = "The forum is exists!";
            //    gridViewForums.DataBind();
            //}
        }

        public void RunParallel(List<int> indexList, int startIndex, int size)
        {
            //Run parallel
            Parallel.For(0, size, i =>
            {
                int rowIndex = indexList[i + startIndex];
                GridViewRow row = gridViewForums.Rows[rowIndex];
                Forum objForum = new Forum();
                objForum.CheckForumInfo((int)gridViewForums.DataKeys[row.RowIndex].Value);
            });

            //init paramaters after run parallel
            startIndex += size;
            if (startIndex + size > indexList.Count)
            {
                size = indexList.Count - startIndex;
                if (size > 0)
                    RunParallel(indexList, startIndex, size);
            }
            else
            {
                RunParallel(indexList, startIndex, size);
            }
        }

        protected void btnCheckInfos_Click(object sender, EventArgs e)
        {
            //Check authentication online
            //BrowserSession br = new BrowserSession_EmptyForum();
            //if (!br.Authentication())
            //  return;

            //Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), row =>
            //{
            //    CheckBox chkBx = (CheckBox)row.FindControl("chkCheckItem");
            //    if (chkBx != null && chkBx.Checked)
            //    {
            //        Forum objForum = new Forum();
            //        objForum.CheckForumInfo((int)gridViewForums.DataKeys[row.RowIndex].Value);
            //    }
            //});
            //gridViewForums.DataBind();

            //Get selected rows to run parallel
            List<int> indexList = new List<int>();
            foreach(GridViewRow row in gridViewForums.Rows)
            {
                CheckBox chkBx = (CheckBox)row.FindControl("chkCheckItem");
                if (chkBx != null && chkBx.Checked)
                    indexList.Add(row.RowIndex);
            }

            //Run parallel with [size] forums every loop
            int startIndex = 0; //index of indexList
            int size = 20; //run maximum 50 forums in indexList for a parallel
            //Check if indexList < default size then update initialization
            if (indexList.Count < size)
                size = indexList.Count;

            //Start run parallel loops
            RunParallel(indexList, startIndex, size);

            //Refresh gridview
            gridViewForums.DataBind();
        }

        protected void btnChangeGroup_Click(object sender, EventArgs e)
        {
            Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
            {
                CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                if (chkBx != null && chkBx.Checked)
                {
                    Forum objForum = new Forum();
                    objForum.ChangeGroup((int)gridViewForums.DataKeys[di.RowIndex].Value, int.Parse(dropDownListChangeGroup.SelectedValue));
                }
            });
            gridViewForums.DataBind();
        }

        

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtForumList.Text))
            {
                string[] forumUrlArray = txtForumList.Text.Split(new char[] { '\n' });
                List<string> forumList = new List<string>();
                foreach (string forumUrl in forumUrlArray)
                {
                    if (!forumList.Contains(forumUrl))
                        forumList.Add(GeneralClass.FormatUrl2(forumUrl));
                }
                Forum objForum = new Forum();
                Dictionary<string, bool> forumDict = objForum.AddForumList(forumList);
                txtForumList.Text = "";
                foreach (KeyValuePair<string, bool> value in forumDict)
                {
                    txtForumList.Text += value.Key + " - " + (value.Value ? "ADD SUCCESS!" : "THE FORUM IS EXIST!") + "\n";
                }
                GroupDropDownList.SelectedIndex = 1;
                //gridViewForums.DataBind();
            }
            
        }

        protected void btnFormatUrl_Click(object sender, EventArgs e)
        {
            Parallel.ForEach<GridViewRow>(gridViewForums.Rows.OfType<GridViewRow>(), di =>
            {
                CheckBox chkBx = (CheckBox)di.FindControl("chkCheckItem");
                if (chkBx != null && chkBx.Checked)
                {
                    di.FindControl("chkCheckItem");
                    Forum objForum = new Forum();
                    objForum.FormatUrl((int)gridViewForums.DataKeys[di.RowIndex].Value);
                    
                }
            });
            gridViewForums.DataBind();
            
        }

        protected void btnRunService_Click(object sender, EventArgs e)
        {
            Forum objForum = new Forum();
            objForum.RunSeriveCheckForumInfo();
        }

        protected void chkCheckItem_CheckedChanged(object sender, EventArgs e)
        {
            Session["ucForum_GridViewForums"] = gridViewForums;
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gridViewForums.Rows)
            {
                CheckBox chkBx = (CheckBox)row.FindControl("chkCheckItem");
                CheckBox chkBxApprove = (CheckBox)row.FindControl("chkIsApproved");
                if (chkBx != null && chkBx.Checked)
                {
                    Forum objForum = new Forum();
                    objForum.ChangeApprove((int)gridViewForums.DataKeys[row.RowIndex].Value, !chkBxApprove.Checked);
                }
            }

            //Refresh gridview
            gridViewForums.DataBind();
        }

       

       

        

    }
}